<template>
  <div>
    <!-- 搜索栏 -->
    <div class="card" style="margin-bottom: 5px">
      <el-input 
        style="width: 240px; margin-right: 10px" 
        v-model="data.questionText" 
        placeholder="请输入题目内容查询" 
        prefix-icon="Search"
      ></el-input>
      <el-select
        style="width: 240px; margin-right: 10px"
        v-model="data.dimension"
        placeholder="请选择测试维度"
        clearable
      >
        <el-option label="EI维度" value="EI" />
        <el-option label="SN维度" value="SN" />
        <el-option label="TF维度" value="TF" />
        <el-option label="JP维度" value="JP" />
      </el-select>
      <el-button type="primary" @click="load">查 询</el-button>
      <el-button type="info" @click="reset">重 置</el-button>
    </div>
    
    <!-- 操作栏 -->
    <div class="card" style="margin-bottom: 5px">
      <el-button type="success" @click="add">新 增</el-button>
      <el-button type="danger" @click="delBatch">批量删除:{{ data.ids.length }}条</el-button>
    </div>
    
    <!-- 数据表格 -->
    <div class="card" style="margin-bottom: 5px">
      <el-table :data="data.questionList" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="questionId" label="题目ID" width="100" />
        <el-table-column prop="questionText" label="题目内容" width="300" show-overflow-tooltip />
        <el-table-column prop="dimension" label="测试维度" width="100">
          <template #default="scope">
            <el-tag :type="getDimensionTagType(scope.row.dimension)">
              {{ scope.row.dimension }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="optionA" label="选项A" width="200" show-overflow-tooltip />
        <el-table-column prop="optionB" label="选项B" width="200" show-overflow-tooltip />
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button @click="update(scope.row)" type="primary" :icon="Edit" circle />
            <el-button @click="del(scope.row.questionId)" type="danger" :icon="Delete" circle />
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <el-pagination
        @size-change="load"
        @current-change="load"
        v-model:current-page="data.pageNum"
        v-model:page-size="data.pageSize"
        :page-sizes="[5, 10, 15, 20]"
        background
        layout="total, sizes, prev, pager, next"
        :total="data.total"
      />
    </div>
    
    <!-- 新增/编辑弹窗 -->
    <el-dialog v-model="data.formVisible" :title="data.form.questionId ? '编辑题目' : '新增题目'" width="600" destroy-on-close>
      <el-form ref="formRef" :rules="data.rules" :model="data.form">
        <el-form-item prop="questionText" label="题目内容" label-width="80px">
          <el-input 
            v-model="data.form.questionText" 
            type="textarea" 
            :rows="3" 
            autocomplete="off" 
            placeholder="请输入题目内容"
          />
        </el-form-item>
        <el-form-item prop="dimension" label="测试维度" label-width="80px">
          <el-select v-model="data.form.dimension" placeholder="请选择测试维度">
            <el-option label="EI维度" value="EI" />
            <el-option label="SN维度" value="SN" />
            <el-option label="TF维度" value="TF" />
            <el-option label="JP维度" value="JP" />
          </el-select>
        </el-form-item>
        <el-form-item prop="optionA" label="选项A" label-width="80px">
          <el-input v-model="data.form.optionA" autocomplete="off" placeholder="请输入选项A内容"/>
        </el-form-item>
        <el-form-item prop="optionB" label="选项B" label-width="80px">
          <el-input v-model="data.form.optionB" autocomplete="off" placeholder="请输入选项B内容"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="data.formVisible = false">取 消</el-button>
          <el-button type="primary" @click="save">保 存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from "vue";
import request from "@/utils/request";
import { ElMessage, ElMessageBox } from 'element-plus';
import { Delete, Edit } from '@element-plus/icons-vue';

const data = reactive({
  questionText: null,
  dimension: null,
  questionList: [],
  pageNum: 1,
  pageSize: 10,
  total: 0,
  formVisible: false,
  form: {},
  ids: [],
  rules: {
    questionText: [
      { required: true, message: '请输入题目内容', trigger: 'blur' }
    ],
    dimension: [
      { required: true, message: '请选择测试维度', trigger: 'change' }
    ],
    optionA: [
      { required: true, message: '请输入选项A内容', trigger: 'blur' }
    ],
    optionB: [
      { required: true, message: '请输入选项B内容', trigger: 'blur' }
    ]
  }
});

// 维度标签类型
const getDimensionTagType = (dimension) => {
  const types = {
    'EI': 'success',
    'SN': 'warning',
    'TF': 'danger',
    'JP': 'info'
  };
  return types[dimension] || '';
};

// 加载数据
const load = () => {
  request.get("/mbtiquestion/selectPage", {
    params: {
      pageNum: data.pageNum,
      pageSize: data.pageSize,
      questionText: data.questionText,
      dimension: data.dimension
    }
  }).then(res => {
    data.questionList = res.data?.list || [];
    data.total = res.data?.total || 0;
  }).catch(err => {
    ElMessage.error('加载数据失败');
  });
};

// 初始化加载
onMounted(() => {
  load();
});

// 重置查询
const reset = () => {
  data.questionText = null;
  data.dimension = null;
  load();
};

// 新增
const add = () => {
  data.form = {};
  data.formVisible = true;
};

// 编辑
const update = (row) => {
  data.form = JSON.parse(JSON.stringify(row));
  data.formVisible = true;
};

// 表单校验
const formRef = ref();

// 保存
const save = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      if (data.form.questionId) {
        updateQuestion();
      } else {
        addQuestion();
      }
    }
  });
};

// 新增请求
const addQuestion = () => {
  request.post("/mbtiquestion/insert", data.form).then(res => {
    if (res.code === '200') {
      ElMessage.success('新增成功');
      data.formVisible = false;
      load();
    } else {
      ElMessage.error(res.msg || '新增失败');
    }
  }).catch(err => {
    ElMessage.error('请求失败');
  });
};

// 更新请求
const updateQuestion = () => {
  request.put("/mbtiquestion/update", data.form).then(res => {
    if (res.code === '200') {
      ElMessage.success('更新成功');
      data.formVisible = false;
      load();
    } else {
      ElMessage.error(res.msg || '更新失败');
    }
  }).catch(err => {
    ElMessage.error('请求失败');
  });
};

// 单个删除
const del = (id) => {
  ElMessageBox.confirm('确定删除该题目吗？删除后数据无法恢复！', '警告', {
    type: 'warning'
  }).then(() => {
    request.delete(`/mbtiquestion/delete/${id}`).then(res => {
      if (res.code === '200') {
        ElMessage.success('删除成功');
        load();
      } else {
        ElMessage.error(res.msg || '删除失败');
      }
    }).catch(err => {
      ElMessage.error('请求失败');
    });
  }).catch(() => {});
};

// 批量选择
const handleSelectionChange = (rows) => {
  data.ids = rows.map(row => row.questionId);
};

// 批量删除
const delBatch = () => {
  if (data.ids.length === 0) {
    ElMessage.warning('请选择要删除的数据');
    return;
  }
  
  ElMessageBox.confirm(`确定删除选中的 ${data.ids.length} 条数据吗？删除后数据无法恢复！`, '警告', {
    type: 'warning'
  }).then(() => {
    request.delete("/mbtiquestion/deleteBatch", { data: data.ids }).then(res => {
      if (res.code === '200') {
        ElMessage.success('批量删除成功');
        load();
      } else {
        ElMessage.error(res.msg || '批量删除失败');
      }
    }).catch(err => {
      ElMessage.error('请求失败');
    });
  }).catch(() => {});
};
</script>

<style scoped>
.card {
  padding: 15px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}
</style>